package com.sskj.trafficcontrol.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.sskj.trafficcontrol.consts.AppRequestConsts;
import com.sskj.trafficcontrol.consts.IntegralLogConsts;
import com.sskj.trafficcontrol.consts.ResultJsonUtil;
import com.sskj.trafficcontrol.model.pojo.*;
import com.sskj.trafficcontrol.model.vo.*;
import com.sskj.trafficcontrol.service.*;
import com.sskj.trafficcontrol.util.*;
import com.sskj.trafficcontrol.util.weather.Weather;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

import java.util.Arrays;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;


/**
 * @author : zhao kuo
 * @date : 2019/1/25 22:25
 * @description :
 */
@RestController
@RequestMapping(value = "/trafficControl", produces = AppRequestConsts.CONTENT_TYPE_JSON, method = RequestMethod.POST)
@PropertySource(value = "classpath:config.properties")
public class TrfficControlController {

    @Value("${file.tipImg.url}")
    private String fileUrl;

    @Autowired
    private TrafficControlService trafficControlService;

    @Autowired
    private TipImgService tipImgService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private UserCarService userCarService;

    @Autowired
    private UserOpenidService userOpenidService;

    @Autowired
    private UserSignService userSignService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private TcIntegralLogService tcIntegralLogService;


    @RequestMapping(value = "/getTrafficControlCitys")
    public String getTrafficControlCitys() {
        final String[] strs = new String[]{"a", "A", "b", "B", "c", "C", "d", "D",
                "e", "E", "f", "F", "g", "G", "h", "H",
                "i", "I", "j", "J", "k", "K", "l", "L",
                "m", "M", "n", "N", "o", "O", "p", "P",
                "q", "Q", "r", "R", "s", "S", "t", "T",
                "u", "U", "v", "V", "w", "W", "x", "X",
                "y", "Y", "z", "Z"};

        List<TcControlCitys> citys = trafficControlService.getTrafficControlCitys();

        List<CityCharInfo> list = new ArrayList<>();

        for (TcControlCitys city : citys) {
            for (int count = 0; count < strs.length; count++) {
                if (city.getCityCode().startsWith(strs[count])) {
                    if (!isExists(list, strs[count + 1])) {
                        CityCharInfo cityCharInfo = new CityCharInfo();
                        cityCharInfo.setIndex(strs[count + 1]);
                        cityCharInfo.getCity().add(city.getCityName());
                        list.add(cityCharInfo);
                    } else {
                        for (int count1 = 0; count1 < list.size(); count1++) {
                            if (list.get(count1).getIndex().equals(strs[count + 1])) {
                                list.get(count1).getCity().add(city.getCityName());
                            }
                        }
                    }
                }
            }
        }

        return ResultJsonUtil.buildSuccessDataJson(list);
    }

    private boolean isExists(List<CityCharInfo> list, String str) {
        for (int count1 = 0; count1 < list.size(); count1++) {
            if (list.get(count1).getIndex().equals(str)) {
                return true;
            }
        }
        return false;
    }

    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/7 14:38
     * @desc   :  获取首页信息
     * @param  :  * @param null
     * @return :
    */
    @RequestMapping(value = "/getTrafficControlInfos")
    public String getTrafficControlInfos(@RequestBody String cityNameStr) {
        JSONObject cityName = (JSONObject) JSONObject.parse(cityNameStr);
        String reqCityName = cityName.get("cityName").toString();

        TotalDtailVO totalDtailVO = new TotalDtailVO();

        TrafficControlBean trafficControlBean = new TrafficControlBean();
        TrafficControlBeanVO trafficControlBeanVO = new TrafficControlBeanVO();
        List<String> weihaoList =  new ArrayList<>();

        LuBangXianingInfoVO xianxing = null;
        if(!cityNameStr.equals("") && cityNameStr!=null){
            //查询数据库获取城市名称
            TcCitys tcCitys = trafficControlService.findByCityName(reqCityName);
            if(tcCitys!=null){
                //获取第三方的数据
                xianxing = LuBangXianxingUtil.getCityXianxingInfo(tcCitys.getCity());
                if(xianxing!=null){

                    List<String> todayLocalXxWeihao = new ArrayList<>();
                    List<String> nextdayLocalXxWeihao = new ArrayList<>();
                    List<String> afterTomorrowLocalXxWeihao = new ArrayList<>();


                    List<String> todayforeignXxWeihao = new ArrayList<>();
                    List<String> nextforeignXxWeihao = new ArrayList<>();
                    List<String> afterTomorrowforeignXxWeihao = new ArrayList<>();

                    List<String> todayAllcarXxWeihao = new ArrayList<>();
                    List<String> nextAllcarXxWeihao = new ArrayList<>();
                    List<String> afterTomorrowAllcarXxWeihao = new ArrayList<>();

                    if(xianxing.getLocalcar().size()!=0){
                        LuBangXianingInfoVO.LocalcarBean localcarBean = xianxing.getLocalcar().get(0);
                        todayLocalXxWeihao = getXxWeihao(localcarBean.getNumber(),0);  //今天
                        nextdayLocalXxWeihao = getXxWeihao(localcarBean.getNumber(),1); //明天
                        afterTomorrowLocalXxWeihao = getXxWeihao(localcarBean.getNumber(),2); //后天
                        trafficControlBeanVO.setLocalRemarks(localcarBean.getSummary());
                    }

                    if(xianxing.getForeigncar().size()!=0){
                        LuBangXianingInfoVO.ForeigncarBean foreigncarBean = xianxing.getForeigncar().get(0);
                        todayforeignXxWeihao = getXxWeihao(foreigncarBean.getNumber(),0);//今天
                        nextforeignXxWeihao = getXxWeihao(foreigncarBean.getNumber(),1);//明天
                        afterTomorrowforeignXxWeihao = getXxWeihao(foreigncarBean.getNumber(),2);//后天
                        trafficControlBeanVO.setForeignRemarks(foreigncarBean.getSummary());
                    }
                    //所有车辆
                    if(xianxing.getAllcars().size()!=0){
                        LuBangXianingInfoVO.AllCarBean allCarBean = xianxing.getAllcars(). get(0);
                        todayAllcarXxWeihao = getXxWeihao(allCarBean.getNumber(),0);
                        nextAllcarXxWeihao = getXxWeihao(allCarBean.getNumber(),1);
                        afterTomorrowAllcarXxWeihao = getXxWeihao(allCarBean.getNumber(),2);
                        trafficControlBeanVO.setAllCarRemarks(allCarBean.getSummary());
                    }

                    //封装限行规则
                    trafficControlBeanVO.setTodayLocalXxWeihao(todayLocalXxWeihao);
                    trafficControlBeanVO.setNextdayLocalXxWeihao(nextdayLocalXxWeihao);
                    trafficControlBeanVO.setAfterTomorrowLocalXxWeihao(afterTomorrowLocalXxWeihao);

                    trafficControlBeanVO.setTodayforeignXxWeihao(todayforeignXxWeihao);
                    trafficControlBeanVO.setNextforeignXxWeihao(nextforeignXxWeihao);
                    trafficControlBeanVO.setAfterTomorrowforeignXxWeihao(afterTomorrowforeignXxWeihao);

                    trafficControlBeanVO.setTodayAllcarXxWeihao(todayAllcarXxWeihao);
                    trafficControlBeanVO.setNextAllcarXxWeihao(nextAllcarXxWeihao);
                    trafficControlBeanVO.setAfterTomorrowAllcarXxWeihao(afterTomorrowAllcarXxWeihao);

                    totalDtailVO.setTrafficControlInfo(trafficControlBeanVO);


                }else{
                    totalDtailVO.setTrafficControlInfo(null);
                }
             }
        }

        //CityWeatherUtil.GetTodayTemperatureByCity(totalDtailVO, cityName.get("cityName").toString());
        // String cityWeatherInfo = CityWeatherUtil.getCityWeatherInfo("");
        String str = HttpClientUtils.getInstance().httpGet(HttpClientUtils.WEATHER_URL + cityName.get("cityName").toString());
        Weather weather = (Weather) XMLUtil.convertXmlStrToObject(Weather.class, str);
        CityWeatherUtil.GetTodayWeatherByCity(totalDtailVO,weather);

        List<Tip> tips = new ArrayList<>();
        Tip ziwaixianTip = new Tip();
        TcTipImg img1 = tipImgService.getImgUrl(5);
        ziwaixianTip.setTipImg(fileUrl + img1.getTipImgUrl());
        ziwaixianTip.setType( "紫外线强度");
        ziwaixianTip.setTitle( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(6).getValue()));
        ziwaixianTip.setContent(UicodeBackslashU.unicodeToCn( weather.getZhishus().getZhishu().get(6).getDetail()));


        Tip jianfeiTip = new Tip();
        TcTipImg img2 = tipImgService.getImgUrl(4);
        jianfeiTip.setTipImg(fileUrl + img2.getTipImgUrl());
        jianfeiTip.setType( "晨练指数");
        jianfeiTip.setTitle( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(0).getValue()));
        jianfeiTip.setContent( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(0).getDetail()));

        Tip jianfeiTip1 = new Tip();
        TcTipImg img3 = tipImgService.getImgUrl(3);
        jianfeiTip1.setTipImg(fileUrl + img3.getTipImgUrl());

        Tip jianfeiTip2 = new Tip();
        TcTipImg img4 = tipImgService.getImgUrl(1);
        jianfeiTip2.setTipImg(fileUrl + img4.getTipImgUrl());
        jianfeiTip2.setType("穿衣指数");
        jianfeiTip2.setTitle( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(2).getValue()));
        jianfeiTip2.setContent( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(2).getDetail()));

        Tip jianfeiTip3 = new Tip();
        TcTipImg img5 = tipImgService.getImgUrl(2);
        jianfeiTip3.setTipImg(fileUrl + img5.getTipImgUrl());
        jianfeiTip3.setType( "洗车指数");
        jianfeiTip3.setTitle( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(7).getValue()));
        jianfeiTip3.setContent( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(7).getDetail()));

        Tip jianfeiTip4 = new Tip();
        TcTipImg img6 = tipImgService.getImgUrl(3);
        jianfeiTip4.setTipImg(fileUrl + img6.getTipImgUrl());
        jianfeiTip4.setType("舒适度");
        jianfeiTip4.setTitle( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(1).getValue()));
        jianfeiTip4.setContent( UicodeBackslashU.unicodeToCn(weather.getZhishus().getZhishu().get(1).getDetail()));


        tips.add(jianfeiTip2);
        tips.add(jianfeiTip3);
        tips.add(jianfeiTip4);
        tips.add(ziwaixianTip);
        tips.add(jianfeiTip);

        totalDtailVO.setTips(tips);

        LocalTime localDate = LocalTime.now();

        totalDtailVO.getToday().setTime(localDate.getHour() < 10 ? ("0" + localDate.getHour()) : localDate.getHour() + ":" + (localDate.getMinute() < 10 ? ("0" + localDate.getMinute()) : localDate.getMinute()));

        return ResultJsonUtil.buildSuccessDataJson(totalDtailVO);
    }

    public static boolean isNumeric(String str){
           for (int i = str.length();--i>=0;){
                    if (!Character.isDigit(str.charAt(i))){
                            return false;
                       }
                }
            return true;
         }

    /**
     * 设置提醒
     * @param noticeTimeStr
     * @return
     */
    @RequestMapping(value = "/setNoticeTime")
    public String setNoticeTime(@RequestBody String noticeTimeStr) throws ParseException {
        JSONObject noticeTimeInfo = (JSONObject) JSONObject.parse(noticeTimeStr);

        String openId = noticeTimeInfo.get("open_id").toString();
        String noticeTime = noticeTimeInfo.get("notice_time").toString();   //
        String noticeType = noticeTimeInfo.get("notice_type").toString();   //0:今日 1：明日

        Integer totalCount = noticeService.selectTotalCount(openId);
        //如果没有推送信息
        if(totalCount==0){
            TcNoticeInfo tcNoticeInfo = new TcNoticeInfo();
            if (noticeType.equals("0")) { //0:今天  1:明天
                tcNoticeInfo.setNoticeTime(getTime(noticeTime));
            } else {
                tcNoticeInfo.setNoticeTime(getTime(noticeTime));
            }

            tcNoticeInfo.setOpenId(openId);
            tcNoticeInfo.setCount(1);
            tcNoticeInfo.setCreateTime(new Date());
            tcNoticeInfo.setModifyTime(new Date());
            tcNoticeInfo.setNoticeType(Integer.parseInt(noticeType));
            noticeService.insertNotice(tcNoticeInfo);
        }else{
            List<TcNoticeInfo> noticeInfos = noticeService.fetchAllNoticeInfos();
            List<TcNoticeInfo> noticeInfoDelay = new ArrayList<>();
            //开始遍历所有的推送消息
            for (int count = 0; count < noticeInfos.size(); count++) {
                if(noticeInfos.get(count).getOpenId().equals(openId)&&noticeInfos.get(count).getCount()==1){
                    TcNoticeInfo tcNoticeInfo = new TcNoticeInfo();
                    if(null!=noticeInfos.get(count).getNoticeTime()){
                        //设置更新时间
                        tcNoticeInfo.setNoticeTime(updateTime(noticeTime, noticeInfos.get(count).getNoticeTime()));
                        tcNoticeInfo.setOpenId(openId);
                        tcNoticeInfo.setModifyTime(new Date());
                        tcNoticeInfo.setConditionTime(noticeInfos.get(count).getNoticeTime());
                        tcNoticeInfo.setNoticeType(Integer.parseInt(noticeType));
                        noticeService.updateNotices(tcNoticeInfo);
                    }else{
                        noticeInfoDelay.add(noticeInfos.get(count));
                    }
                }
            }
            for (int count = 0; count < noticeInfoDelay.size(); count++) {
                TcNoticeInfo tcNoticeInfo = new TcNoticeInfo();
                TcNoticeInfo tcNoticeInfo1 = noticeService.zuijinshijian(openId);
                if(null==tcNoticeInfo1.getNoticeTime()){
                    LocalDate localDate = LocalDate.now();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    tcNoticeInfo.setNoticeTime( df.parse(localDate.toString() + " " + noticeTime + ":00"));
                }else{
                    tcNoticeInfo.setNoticeTime(calNoticeTime(tcNoticeInfo1.getNoticeTime()));
                }
                tcNoticeInfo.setOpenId(openId);
                tcNoticeInfo.setFormId(noticeInfoDelay.get(count).getFormId());
                tcNoticeInfo.setNoticeType(Integer.parseInt(noticeType));
                noticeService.updateNoticeform(tcNoticeInfo);
            }
        }

        return ResultJsonUtil.buildSuccessDataJson("设置成功");
    }

    private Date updateTime(String noticeTime, Date noticeTime1) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1 = df.format(noticeTime1);
        return df.parse(time1.substring(0,11)+noticeTime+":00");
    }


    private boolean isExistsNotice(String openId, String noticeTime) {

        return false;
    }

    //获取微信的OpenId
    @RequestMapping(value = "/getOpenId")
    public String getOpenId(@RequestBody String codeStr) throws Exception {
        JSONObject code = (JSONObject) JSONObject.parse(codeStr);
        //获取被邀请对象
        String inviCodeOPenId = null;
        Object inviCodeOPenIdStr = code.get("inviCodeOPenIdStr");
        if(inviCodeOPenIdStr!=null && !"".equals(inviCodeOPenIdStr.toString())){
            inviCodeOPenId = code.get("inviCodeOPenIdStr").toString();
        }

//调用访问微信服务器工具方法，传入三个参数获取带有openid、session_key的json字符串
        String jsonId = getOpenIdutil.getopenid(getOpenIdutil.appid, code.get("code").toString(), getOpenIdutil.secret);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonId);
//从json字符串获取openid和session_key
        String openid = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        //判断用户是否是第一次登陆注册
        TcUserOpenId tcUserOpenId = userOpenidService.getOpenId(openid);

        //排除自己邀请自己
        if(inviCodeOPenId!=null && !"".equals(inviCodeOPenId) && inviCodeOPenId.equals(openid)){
            inviCodeOPenId = null;
        }
        if(tcUserOpenId==null){
            //第一次进入 相当于注册
            userOpenidService.registUser(openid,inviCodeOPenId);
            //初始化 签到表直接签到一次
            userSignService.addUserSign(openid,DateUtil.getDateZeroStr());
            //第一次更新积分日志
            addTcIntegralLog(openid,1, IntegralLogConsts.INTEGRALLOG_USER_SIGN);

        }else{
            //签到
            if(tcUserOpenId.getTcOpenid()!=null){
                TcUserSign userSign = userSignService.getUserSign(openid);
                Date tcSignLastTime = userSign.getTcSignLastTime(); //上次登录日期 2018-09-09 23:59:59
                Date dateZero = DateUtil.getDateZero(); //今日零点的日期 2018-09-10 23:59:59
                if(dateZero.getTime()/1000>tcSignLastTime.getTime()/1000){ //秒级处理
                    //更新积分
                    userIntegralService.updateUserIntegral(openid);
                    //更新签到日期 签到次数
                    userSignService.updateSignDate(userSign.getTcOpenid(),DateUtil.getDateStr(dateZero));
                    //更新积分日志
                    addTcIntegralLog(openid,1, IntegralLogConsts.INTEGRALLOG_USER_SIGN);
                }
            }
        }

        GetOpenIdVO getOpenIdVO = new GetOpenIdVO();
        getOpenIdVO.setOpenid(openid);
        getOpenIdVO.setSession_key(session_key);
        return ResultJsonUtil.buildSuccessDataJson(getOpenIdVO);
    }



    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/7 18:42
     * @desc   : 解密获取用户手机号码
     * @param  :  * @param null
     * @return :
    */
    @RequestMapping(value = "/dissect")
    public String getPhoneNumber(@RequestBody String paramJson) {
        try {
            JSONObject  paramObj = (JSONObject) JSONObject.parse(paramJson);
            //获取被邀请对象
            String encryptedData = paramObj.get("encryptedData").toString();
            String session_key = paramObj.get("session_key").toString();
            String iv = paramObj.get("iv").toString();

            //HttpUtil.getOpenid这个方法是我自己封装的方法，传入code后然后获取openid和session_key的，把他们封装到json里面
            if (session_key != null) {
                // 被加密的数据
                byte[] dataByte = Base64.decode(encryptedData);
                // 加密秘钥
                byte[] keyByte = Base64.decode(session_key);
                // 偏移量
                byte[] ivByte = Base64.decode(iv);
                try {
                    // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
                    int base = 16;
                    if (keyByte.length % base != 0) {
                        int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                        byte[] temp = new byte[groups * base];
                        Arrays.fill(temp, (byte) 0);
                        System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                        keyByte = temp;
                    }
                    // 初始化
                    Security.addProvider(new BouncyCastleProvider());
                    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                    SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
                    AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
                    parameters.init(new IvParameterSpec(ivByte));
                    cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
                    byte[] resultByte = cipher.doFinal(dataByte);
                    if (null != resultByte && resultByte.length > 0) {
                        String result = new String(resultByte, "UTF-8");
                        //获取手机号码
                        return ResultJsonUtil.buildSuccessDataJson(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }




    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/6 9:58
     * @desc   :  绑定车牌（自己的OPenId）
     * @param  :  * @param null
     * @return :
    */
    @RequestMapping(value = "/bindCarNumber")
    public String bindCarNumber(@RequestBody String bindCarNumberStr){

        JSONObject bindCarNumber = (JSONObject)JSONObject.parse(bindCarNumberStr);
        String open_id = bindCarNumber.get("open_id").toString();

        String carNumber = null;
        String userMobile = null;
        if(bindCarNumber.get("carNumber")!=null){
            carNumber = bindCarNumber.get("carNumber").toString();
        }
        if(bindCarNumber.get("userMobile")!=null){
            userMobile = bindCarNumber.get("userMobile").toString();
        }


        String carnumber = userCarService.getCarNumber(open_id);
        if(carnumber!=null || "".equals(carnumber)){
            return ResultJsonUtil.buildSuccessDataJson("bind", "carnumber already have");
        }else{
            int result = userCarService.bindCarNumber(open_id,carNumber,userMobile);
            if(result>0){
                TcUserOpenId openId = userOpenidService.getOpenId(open_id);
                if(openId.getTcInviteOpenId()!=null && !"".equals(openId.getTcInviteOpenId())){
                    //更新积分
                    userIntegralService.updateUserIntegral(openId.getTcInviteOpenId());
                    //更新积分日志
                    addTcIntegralLog(openId.getTcInviteOpenId(),1, IntegralLogConsts.INTEGRALLOG_USER_INVITE);
                }
            }
            return ResultJsonUtil.buildSuccessDataJson("bind", "success");
        }
    }


    /**
     * 设置提醒次数
     * @param addNoticeCountStr
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/addNoticeCount")
    public String addNoticeCount(@RequestBody String addNoticeCountStr) throws ParseException {
        JSONObject addNoticeCount = (JSONObject) JSONObject.parse(addNoticeCountStr);

        String open_id = addNoticeCount.get("open_id").toString();
        String form_id = addNoticeCount.get("form_id").toString();
        String notice_city = addNoticeCount.get("notice_city").toString();

        TcNoticeInfo tcNoticeInfo = noticeService.selectFormIdIsNull(open_id);
        String carNumber = null;
        if (null == tcNoticeInfo) {
            Integer totalCount = noticeService.selectTotalCount(open_id);
            if(open_id!=null){
                carNumber = userCarService.getCarNumber(open_id);
            }
            if (totalCount >= 7) {
                return ResultJsonUtil.buildErrorJson("小程序提醒不可以超过7天");
            }
            TcNoticeInfo tcNoticeInfo1 = noticeService.selectFormIdIsExists(open_id);
            if(tcNoticeInfo1==null){
                TcNoticeInfo tcNoticeInfo2 = new TcNoticeInfo();
                tcNoticeInfo2.setOpenId(open_id);
                tcNoticeInfo2.setFormId(form_id);
                tcNoticeInfo2.setNoticeCity(notice_city);
                tcNoticeInfo2.setNoticeTime(null);
                tcNoticeInfo2.setCreateTime(new Date());
                tcNoticeInfo2.setCount(1);
                tcNoticeInfo2.setModifyTime(new Date());
                tcNoticeInfo2.setUserCarNumber(carNumber);
                noticeService.insertNotice(tcNoticeInfo2);
            }else{
                tcNoticeInfo1.setFormId(form_id);
                if(tcNoticeInfo1==null||tcNoticeInfo1.getNoticeTime()==null){
                    tcNoticeInfo1.setNoticeTime(null);
                    tcNoticeInfo1.setNoticeCity(notice_city);
                    tcNoticeInfo1.setCreateTime(new Date());
                    tcNoticeInfo1.setCount(1);
                    tcNoticeInfo1.setModifyTime(new Date());
                    tcNoticeInfo1.setUserCarNumber(carNumber);
                    noticeService.insertNotice(tcNoticeInfo1);
                }else{
                    tcNoticeInfo1.setNoticeCity(notice_city);
                    tcNoticeInfo1.setNoticeTime(calNoticeTime(tcNoticeInfo1.getNoticeTime()));
                    tcNoticeInfo1.setCreateTime(new Date());
                    tcNoticeInfo1.setCount(1);
                    tcNoticeInfo1.setModifyTime(new Date());
                    tcNoticeInfo1.setUserCarNumber(carNumber);
                    noticeService.insertNotice(tcNoticeInfo1);
                }
            }
        } else {
            //查询总数
            Integer totalCount = noticeService.selectTotalCount(open_id);
            if (totalCount >= 7) {
                return ResultJsonUtil.buildErrorJson("小程序提醒不可以超过7天");
            }
            tcNoticeInfo.setFormId(form_id);
            tcNoticeInfo.setNoticeCity(notice_city);
            tcNoticeInfo.setUserCarNumber(carNumber);
            noticeService.updateNotice(tcNoticeInfo);
        }

        Integer totalCount = noticeService.selectTotalCount(open_id);

        return ResultJsonUtil.buildSuccessDataJson("noticeCount", totalCount.toString());
    }

    private Date calNoticeTime(Date noticeTime) throws ParseException {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(noticeTime);
        rightNow.add(Calendar.DAY_OF_YEAR, 1);

        return rightNow.getTime();
    }


    @RequestMapping(value = "/setNoticeFlag")
    public String setNoticeFlag(@RequestBody String setNoticeFlagStr) {
        JSONObject setNoticeFlag = (JSONObject) JSONObject.parse(setNoticeFlagStr);

        String open_id = setNoticeFlag.get("open_id").toString();
        String is_open = setNoticeFlag.get("is_open").toString();

        noticeService.updateNoticeStatus(open_id, is_open);

        return ResultJsonUtil.buildSuccessDataJson("update", "success");
    }

    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/5 18:20
     * @desc   :  修改车辆信息biao
     * @param  :  * @param null
     * @return :
    */
    @RequestMapping(value = "/eidtCarNumber")
    public String editCarNumber(@RequestBody String editCarNumStr){
        JSONObject editCarNum = (JSONObject) JSONObject.parse(editCarNumStr);
        int result = 0 ;
        if(editCarNum!=null){
            String open_id = editCarNum.get("open_id").toString();
            String carNumber = editCarNum.get("carNumber").toString();
            result =  userCarService.editCarNumber(open_id,carNumber);
        }
        return ResultJsonUtil.buildSuccessDataJson("update", result>=1?"true":"false");
    }


    /**
     * 限行设置数据回显接口
     * @param getNoticeInfoStr
     * @return
     */
    @RequestMapping(value = "/getNoticeInfo")
    public String getNoticeInfo(@RequestBody String getNoticeInfoStr) {
        JSONObject getNoticeInfo = (JSONObject) JSONObject.parse(getNoticeInfoStr);

        NoticeConfig noticeConfig = new NoticeConfig();

        String open_id = getNoticeInfo.get("open_id").toString();

        Integer totalCount = noticeService.selectTotalCount(open_id);
        List<TcNoticeInfo> tcNoticeInfos = noticeService.fetchAllNoticeInfos();
        for(TcNoticeInfo tcNoticeInfo: tcNoticeInfos){
            if(tcNoticeInfo.getOpenId().equals(open_id)){
                noticeConfig.setNoticeCount(totalCount.toString());
                noticeConfig.setNoticeFlag(tcNoticeInfo.getPushStatus()!=null?tcNoticeInfo.getPushStatus().toString():"0");
                noticeConfig.setNoticeTime(transTime(tcNoticeInfo.getNoticeTime()));
                noticeConfig.setNoticeType(tcNoticeInfo.getNoticeType()!=null?tcNoticeInfo.getNoticeType().toString():"0");
            }
        }
        //反显车辆信息
        String carNumber = userCarService.getCarNumber(open_id);
        noticeConfig.setCarNumber(carNumber);
        return ResultJsonUtil.buildSuccessDataJson(noticeConfig);
    }


    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/6 21:50
     * @desc   :  展示用户的总积分 积分日志列表
     * @param  :  * @param null
     * @return :
    */
    @RequestMapping(value = "/userIntegralInfo")
    public String userIntegralInfo(@RequestBody String userIntegral){
        JSONObject getNoticeInfo = (JSONObject) JSONObject.parse(userIntegral);
        String open_id = getNoticeInfo.get("open_id").toString();

        UserIntegralVo userIntegralVo = new UserIntegralVo();
        //总积分
        int totalIntegral =  userIntegralService.getTotalIntegral(open_id);
        //积分列表
        List<TcIntegralLog> integralLogList = tcIntegralLogService.getIntegralLog(open_id);
        userIntegralVo.setTotalIntegral(totalIntegral);
        userIntegralVo.setIntegralLogList(integralLogList);
        return ResultJsonUtil.buildSuccessDataJson(userIntegralVo);
    }

    private String transTime(Date noticeTime) {

        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        return noticeTime!=null?df.format(noticeTime).substring(0,5):"00:00";
    }


    public Date getTime(String args) throws ParseException {
//        if (type.equals(0)) {
            LocalDate localDate = LocalDate.now();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.parse(localDate.toString() + " " + args + ":00");
//        }
//        else {
//            LocalDate localDate = LocalDate.now();
//            localDate = localDate.plusDays(Integer.parseInt(type));
//            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            return df.parse(localDate.toString() + " " + args + ":00");
//        }
    }

    /**
     * 截取尾号
     * @param number
     * @return
     */
    private List<String> getXxWeihao(String number,int num){
        String[] split = number.split(";");
        List<String> resultList = new ArrayList<>(2);
        String[] weihao = null;
        if("不限行".equals(split[num])){
            weihao = new String[]{"-1"};   //不限行
        }else if("所有号牌".equals(split[num])){
            weihao = new String[]{"-2"};   //所有车牌
        }else{
            weihao = split[num].split(",");   //进行分割
        }
        Collections.addAll(resultList,weihao);
        return resultList;
    }


    public void addTcIntegralLog(String openId,int integral,String direction){
        TcIntegralLog tcIntegralLog = new TcIntegralLog();
        tcIntegralLog.setTcOpenid(openId);
        tcIntegralLog.setTcIntegralFlag(1); //增加1
        tcIntegralLog.setTcIntegerNum(integral);
        tcIntegralLog.setTcDirection(direction);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        tcIntegralLog.setTcAddtime(calendar.getTime());
        tcIntegralLogService.addTcIntegralLog(tcIntegralLog);
    }





}
